package com.andy.eqm.server.game;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.andy.eqm.server.dao.DaoUtils;
import com.andy.eqm.server.entity.UsrUser;
import com.andy.eqm.server.socket.MySocketSession;
import com.andy.eqm.server.utils.GoConstant;
import com.andy.eqm.server.web.controller.BaseController;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

public class Global implements Serializable{

	private static final long serialVersionUID = 1L;
	
	private static Logger logger = LoggerFactory.getLogger(Global.class);
	
	/**
	 * 在线人数
	 */
	public static AtomicInteger onlineNumber = new AtomicInteger();

	private static Map<Long,MySocketSession> sessionMap = Maps.newConcurrentMap();
	private static List<MySocketSession> sessions = Lists.newCopyOnWriteArrayList();
	
	public static void addSession(MySocketSession session){
		onlineNumber.incrementAndGet();
		sessions.add(session);
		
		if(logger.isInfoEnabled()){
			logger.info("有新连接加入！ 当前在线人数：{}，s={}", onlineNumber,sessions.size());
		}
	}
	
	public static void removeSession(MySocketSession session){
		if(sessions.remove(session)){
			onlineNumber.decrementAndGet();
		}
		GameUser user = session.getUser();
		if(user != null){
			sessionMap.remove(user.getId());
			session.removeAttr(GoConstant.USER_SESSION_KEY);
			if(logger.isInfoEnabled()){
				logger.info("断开连接用户：{}-{}", user.getId(),session);
			}
		}
		
		if(logger.isInfoEnabled()){
			logger.info("有连接关闭！ 当前在线人数：{},s={},u={}", onlineNumber,sessions.size(),sessionMap.size());
		}
	}
	
	public static void addUser(Long uid,MySocketSession session){
		if(logger.isInfoEnabled()){
			logger.info("登录用户：{}-{}", uid,session);
			logger.info("当前在线人数{},s={},u={}", onlineNumber,sessions.size(),sessionMap.size());
		}
		sessionMap.put(uid, session);
	}
	
	public static MySocketSession getSession(long id){
		return sessionMap.get(id);
	}
	
	public static Collection<MySocketSession> getUserSessions(){
		return sessionMap.values();
	}

	public static AtomicLong sysCurrHave ;
	

	private static List<Map<String, Object>> ranks = Lists.newArrayList();
	public static List<Map<String, Object>> getRanks() {
		return ranks;
	}

	public static void refreshRanks() {
		List<Map<String, Object>> ranksT = DaoUtils.getListSql( "select uid,win_count as winCount,title from usr_game_info order by win_count desc limit 0,10");
		BaseController.idToName(ranksT, UsrUser.table(), "uid#id:icon,nick_name as nickName");
		ranks = ranksT;
	}

	
}
